-- dungeon_event
-- Created by chengb Sep/11/2015
-- 成就：迷宫事件

-- 内部函数声明
local whenDungeonAchivComplete;

-- 注册完成迷宫事件的回调
EventMgr.register("game_achievement/dungeon_event", event.ACHIV_COMPLETE, function(args)
    whenDungeonAchivComplete(args);
end);

-- 注册完成迷宫事件的回调
whenDungeonAchivComplete = function(args)
    if not DungeonM.isInDungeon() then
        return false;
    end

    local dungeonId = DungeonM.getDungeonId();
    local parentId = DungeonAreaM.getParentId(dungeonId);

    -- 判断是否是符合要求的成就
    local function isValidId(id)
        if true == GameAchievementM.isCompleted(id) then
            -- 已经完成了
            return false;
        end

        local config = GameAchievementM.query(id);
        local ruleArg = config["rule_arg"];
        if type(ruleArg) == 'table' then
            if type(ruleArg["dungeon_id"]) ~= 'number' then
                -- 未配置迷宫编号
                return false;
            end

            if ruleArg["dungeon_id"] ~= parentId then
                -- 不是需求的迷宫事件
                return false;
            end

            if type(ruleArg["dp"]) == 'number' then
                local curDp = AchievementM.calcCurDp(parentId);
                if curDp < ruleArg["dp"] then
                    -- dp值未达标
                    return false;
                end
            end
        end

        return true;
    end

    -- 遍历所有的子规则
    local ids = GameAchievementM.getIdsByRule("dungeon_event");
    for _, id in pairs(ids) do
        if isValidId(id) then
            -- 尝试完成成就
            GameAchievementM.tryComplete(id, 1);
        end
    end
end

return {
    -- 获取成就描述
    queryDesc = function(id)
        local config = GameAchievementM.query(id);

        local ruleArg = config["rule_arg"];
        local dp      = ruleArg["dp"];
        local desc    = config["desc"];

        desc = string.gsub(desc, "{dungeon}", DungeonAreaM.query(ruleArg.dungeon_id, "name"));
        desc = string.gsub(desc, "{dp}", dp);

        return desc;
    end,
};